<template>
  <view class="orderList">
    <view :orderData="orderData" :change:orderData="renderScript.orderDataChange" />
    <view :outOrderData="outOrderData" :change:outOrderData="renderScript.orderDataChange" />
    <web-view v-if="show" :src="pageUrl" @message="receiveMessage" />
  </view>
</template>
<script>
import { webviewBaseUrl, getSaleOrderList } from '../../config/api';
import moment from 'moment';
export default {
  data() {
    return {
      pageUrl: '',
      show: true,
      orderData: { orderList: [] },
      outOrderData: { orderList: [] }
    };
  },
  onLoad() {
    uni.setNavigationBarTitle({ title: '订单列表' });
    let username = uni.getStorageSync('username');
    this.pageUrl = `${webviewBaseUrl}/orderList?type=${username === 'NTC001'}&time=${new Date().getTime()}`;
  },
  onShow() {
    let page = uni.getStorageSync('page');
    if (page !== 'orderList') {
      uni.setStorageSync('page', 'orderList');
      this.show = false;
      let uid = setTimeout(() => {
        this.show = true;
      }, 100);
    }
    let cellInfo = uni.getStorageSync('cellInfo') || { cell1: '21.78', cell2: '57.78', cell3: '63.77', cell4: '213.77', cell5: '45.79', cell6: '27.82', cell7: '27.82', cell8: '63.78', cell9: '75.78' };
    let wpx = [];
    let list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    list.forEach(el => {
      wpx.push({ wpx: cellInfo[`cell${el}`] });
    });
  },
  methods: {
    async receiveMessage(event) {
      // #ifdef APP-PLUS
      if (event.detail.data) {
        let res = await getSaleOrderList(event.detail.data[0][1]);
        if (event.detail.data[0][0] === 'list') {
          this.exportList(event.detail.data[0][2], res.data.data);
        } else {
          this.exportOutOrder(event.detail.data[0][2], event.detail.data[0][3], res.data.data);
        }
      }
      // #endif
    },
    //导出清单
    exportList(ids, orders) {
      let orderList = [];
      let wpx = [{ wpx: 220 }, { wpx: 70 }, { wpx: 75 }, { wpx: 220 }, { wpx: 70 }, { wpx: 200 }, { wpx: 120 }, { wpx: 300 }, { wpx: 140 }, { wpx: 60 }, { wpx: 50 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 60 }, { wpx: 200 }, { wpx: 50 }, { wpx: 145 }, { wpx: 50 }, { wpx: 630 }];
      let arr = []; //所选中的订单
      ids.forEach(el => {
        arr.push(orders[el]);
      });
      orderList.push(['公司', '业务员', '日期', '客户单位', '采购人', '品牌', '货号', '名称', '规格', '数量', '计量单位', '拿货单价', '拿货总价', '客户单价', '客户总价', '毛利', '供货商', '进项票', '发票号', '是否回款', '备注']);
      arr.map(item => {
        orderList.push([item.companyName, item.companySaleName, item.dateInput, item.customerName, item.customerPurchaserName, item.productBrandName, item.productBrandArticleNo, item.productBrandArticleNoName, item.productSpecificationName, item.qty, item.unit, item.purchaseSinglePrice, item.purchaseTotalPrice, item.customerSinglePrice, item.customerTotalPrice, Number(item.customerTotalPrice) - Number(item.purchaseTotalPrice), item.productSupplierName, item.purchaseInvoice === '1' ? '是' : '否', item.invoiceNo, item.purchaseInvoiceReceive === '1' ? '是' : '否', item.remark]);
      });
      this.orderData = { orderList: [] };
      let uid = setTimeout(() => {
        clearTimeout(uid);
        this.orderData = { orderList, wpx, name: '订单' };
      }, 200);
    },
    //导出出库单
    async exportOutOrder(ids, info, orders) {
      let cellInfo = uni.getStorageSync('cellInfo') || { cell1: '21.78', cell2: '57.78', cell3: '63.77', cell4: '213.77', cell5: '45.79', cell6: '27.82', cell7: '27.82', cell8: '63.78', cell9: '75.78' };
      let orderList = [];
      let wpx = [];
      let list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      list.forEach(el => {
        wpx.push({ wpx: cellInfo[`cell${el}`] });
      });
      let arr = []; //所选中的订单
      ids.forEach(el => {
        arr.push(orders[el]);
      });
      orderList.push([arr[0].companyName, , '', '', '', '', '', '', '', '']);
      orderList.push(['销售出库单', '', '', '', '', '', '', '', '']);
      orderList.push(['客户名称：', '', arr[0].customerName, '', `收货人：${arr[0].customerPurchaserName}`, '', '', `电话：${arr[0].customerPurchaserPhone}`, '']);
      orderList.push(['收货地址：', '', arr[0].customerAddress, '', '', '', '', `制单日期：${moment().format('YYYY-MM-DD')}`, '']);
      orderList.push(['序号', '品牌', '货号', '品名', '规格', '单位', '数量', '含税单价', '总价']);
      let totalNum = 0;
      let totalPrice = 0;
      arr.map((item, idx) => {
        totalNum += Number(item.qty);
        totalPrice += Number(item.customerTotalPrice);
        orderList.push([idx + 1, item.productBrandName, item.productBrandArticleNo, item.productBrandArticleNoName, item.productSpecificationName, item.unit, Number(item.qty).toFixed(0), item.customerSinglePrice, item.customerTotalPrice]);
      });
      orderList.push(['', '合计', '', '', '', '', totalNum.toFixed(0), '', totalPrice.toFixed(2)]);
      orderList.push(['客户\n须知', '1、尊敬的客户，您好！以上是您所购的产品,请当面清点并核对发票。\n2、若无异议，请安排付款，付款请注明发票号，谢谢！\n3、若有货物缺少或损坏的情况，请在收到货物起三日内与我公司联系。', '', '', '供销\n单位', '公司名称', '', arr[0].companyName, '']);
      orderList.push(['', '', '', '', '', '纳税人识别号', '', info.taxNo, '']);
      orderList.push(['', '', '', '', '', '开户行', '', info.address, '']);
      orderList.push(['', '', '', '', '', '', '', info.bank, '']);
      orderList.push(['', '业务员：', arr[0].companySaleName, `电话：${info.companySalePhone}`, '签收人：', '', '', '日期', '']);
      let merges = [
        { s: { c: 0, r: 0 }, e: { c: 8, r: 0 } },
        { s: { c: 0, r: 1 }, e: { c: 8, r: 1 } },
        { s: { c: 0, r: 2 }, e: { c: 1, r: 2 } },
        { s: { c: 2, r: 2 }, e: { c: 3, r: 2 } },
        { s: { c: 4, r: 2 }, e: { c: 6, r: 2 } },
        { s: { c: 7, r: 2 }, e: { c: 8, r: 2 } },
        { s: { c: 0, r: 3 }, e: { c: 1, r: 3 } },
        { s: { c: 2, r: 3 }, e: { c: 6, r: 3 } },
        { s: { c: 7, r: 3 }, e: { c: 8, r: 3 } },
        { s: { c: 0, r: arr.length + 6 }, e: { c: 0, r: arr.length + 9 } },
        { s: { c: 1, r: arr.length + 6 }, e: { c: 3, r: arr.length + 9 } },
        { s: { c: 4, r: arr.length + 6 }, e: { c: 4, r: arr.length + 9 } },
        { s: { c: 5, r: arr.length + 6 }, e: { c: 6, r: arr.length + 6 } },
        { s: { c: 7, r: arr.length + 6 }, e: { c: 8, r: arr.length + 6 } },
        { s: { c: 5, r: arr.length + 7 }, e: { c: 6, r: arr.length + 7 } },
        { s: { c: 7, r: arr.length + 7 }, e: { c: 8, r: arr.length + 7 } },
        { s: { c: 5, r: arr.length + 8 }, e: { c: 6, r: arr.length + 9 } },
        { s: { c: 7, r: arr.length + 8 }, e: { c: 8, r: arr.length + 8 } },
        { s: { c: 7, r: arr.length + 9 }, e: { c: 8, r: arr.length + 9 } }
      ];
      this.outOrderData = { orderList: [] };
      let uid = setTimeout(() => {
        clearTimeout(uid);
        this.outOrderData = { orderList, dataLen: arr.length, merges, wpx, name: '出库单' };
      }, 200);
    },
    writeOver({ filePath, name, date, fileName }) {
      let fileList = uni.getStorageSync(name === '订单' ? 'order' : 'outOrder') || [];
      fileList.unshift({ filePath, name, date, fileName });
      this.orderData = { orderList: [] };
      this.outOrderData = { orderList: [] };
      uni.setStorageSync(name === '订单' ? 'order' : 'outOrder', fileList);
      uni.showToast({ title: '导出成功', icon: 'success', duration: 2000 });
    }
  }
};
</script>
<script module="renderScript" lang="renderjs">
import XLSX from '../../utils/xlsx.bundle.js';
import { JsonToFileData } from '../../utils/excel';
export default {
  methods: {
    getBold({ i, cell }) {
      let data = false
      let list = ['A1', 'A2', 'A3', 'A4', 'E3','H3', 'H4']
      if (list.findIndex(item => item === cell) !== -1) {
        data = true
      } else if (i === 5) {
        data = true
      }
      return data
    },
    getHorizontal({ i, cell, len }) {
      let data = 'left'
      let list = ['A1', 'A2', `E${7 + len}`]
      if (list.findIndex(item => item === cell) !== -1) {
        data = 'center'
      } else if (i > 4 && i < len + 7) {
        data = 'center'
      }
      return data
    },
    getSZ({ i, cell, len }) {
      let data = 9
      if (i === 3 || i === 4) {
        data = 10
      } else if (cell === 'A1' || cell === 'A2') {
        data = 14
      } else if (i > 6 + len || i < 11 + len) {
        data = 8
      }
      return data
    },
    getBorder({ i, cell, max }) {
      let data = {}
      if (i > 4 && i !== max) {
        data = {
          top: { style: 'thin', color: '#000000' },
          bottom: { style: 'thin', color: '#000000' },
          left: { style: 'thin', color: '#000000' },
          right: { style: 'thin', color: '#000000' }
        }
      }
      return data
    },
    orderDataChange(nv, ov, ownerInstance, vm) {
      let data = JSON.parse(JSON.stringify(nv))
      if (data.orderList && data.orderList.length > 0) {
        let worksheet = XLSX.utils.json_to_sheet(data.orderList, { skipHeader: true })
        if (data.name === '订单') {
          for (const key in worksheet) {
            if (worksheet[key] instanceof Object) {
              worksheet[key].s = {
                alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
                font: { name: '宋体', sz: 10, color: { rgb: '#FF000000' }, bold: false, italic: false, underline: false }
              }
            }
          }
        } else {
          let zm = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
          for (let i = 1; i < data.dataLen + 12; i++) {
            for (let j = 0; j < zm.length; j++) {
              worksheet[`${zm[j]}${i}`].s = {
                alignment: { vertical: 'center', horizontal: this.getHorizontal({ i, cell: `${zm[j]}${i}`, len: data.dataLen }), indent: 0, wrapText: true },
                font: { name: '宋体', sz: this.getSZ({ i, cell: `${zm[j]}${i}`, len: data.dataLen }), color: { rgb: '#FF000000' }, bold: this.getBold({ i, cell: `${zm[j]}${i}` }), italic: false, underline: false },
                border: this.getBorder({ i, max: data.dataLen + 11 })
              }
            }
          }
        }
        worksheet['!merges'] = data.merges
        worksheet['!cols'] = data.wpx
        JsonToFileData({ worksheet, data, ownerInstance })
      }
    }
  }
};
</script>
